<template>
  <div class="message-display">
    <!-- 消息区域 - 优化为增量加载 -->
  <div class="messages-container" ref="messagesContainer">
    <!-- 空状态 -->
    <div v-if="effectiveMessages.length === 0" class="empty-messages">
      <div class="empty-icon">💬</div>
      <h3>开始对话吧</h3>
      <p>输入您的问题，我会尽力为您提供帮助</p>
    </div>

    <!-- 消息列表 - 优化增量加载性能 -->
    <div v-else class="messages">
      <div
        v-for="message in effectiveMessages"
        :key="message.id"
        :class="[
          'message-item',
          { 'user-message': message.role === 'user', 'system-message': message.role === 'assistant' }
        ]"
      >
        <!-- 头像 -->
        <div class="message-avatar">
          <div v-if="message.role === 'user'" class="avatar user-avatar">
            👤
          </div>
          <div v-else class="avatar system-avatar">
            🤖
          </div>
        </div>

        <!-- 消息内容 -->
        <div class="message-content">
          <!-- 加载状态 -->
          <div v-if="message.status === 'loading'" class="message-loading">
            <div class="loading-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
          
          <!-- 完成状态 -->
          <div v-else class="message-text" v-html="formatMessageContent(message.content)"></div>
          
          <!-- 错误状态 -->
          <div v-if="message.status === 'error'" class="message-error">
            ❌
            <span>消息处理出现问题</span>
          </div>
        </div>

        <!-- 消息操作 -->
        <div class="message-actions">
          <button 
            v-if="message.role === 'assistant' && message.status === 'completed'"
            @click="copyMessage(message.content)"
            class="action-button"
            title="复制"
          >
            📋
          </button>
        </div>
      </div>
    </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-wrapper">
        <textarea
          v-model="newMessage"
          @keydown.enter.prevent="handleEnterKey"
          placeholder="输入您的问题..."
          rows="1"
          class="message-input"
          :disabled="isLoading"
        ></textarea>
        <button
          @click="sendMessage"
          :disabled="!newMessage.trim() || isLoading"
          class="send-button"
          title="发送"
        >
          →
        </button>
      </div>
      <div class="input-info">
        <span v-if="isLoading" class="loading-text">正在处理...</span>
        <span v-else class="help-text">按 Enter 发送，Shift + Enter 换行</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted, computed } from 'vue';
// 移除所有Heroicons导入以避免错误

// Props
const props = defineProps({
  conversation: {
    type: Object,
    default: null
  },
  messages: {
    type: Array,
    default: () => []
  },
  isLoading: {
    type: Boolean,
    default: false
  }
});

// 从conversation中获取messages
const effectiveMessages = computed(() => {
  if (props.conversation && props.conversation.messages) {
    return props.conversation.messages;
  }
  return props.messages || [];
});

// 从conversation中获取conversationId
const conversationId = computed(() => {
  return props.conversation ? props.conversation.id : null;
});

// Emits
const emit = defineEmits(['send-message']);

// 响应式数据
const newMessage = ref('');
const messagesContainer = ref(null);
const copyNotification = ref('');

// 监听消息变化，自动滚动到底部 - 优化增量加载体验
watch(effectiveMessages, () => {
  nextTick(() => {
    // 只有当有新消息时才滚动到底部
    const hasNewMessage = effectiveMessages.value.some(msg => 
      msg.status === 'loading' || (msg.status === 'completed' && Date.now() - new Date(msg.timestamp).getTime() < 1000)
    );
    if (hasNewMessage) {
      scrollToBottom();
    }
  });
}, { deep: true });

// 监听会话变化，清空输入框
watch(conversationId, () => {
  newMessage.value = '';
});

// 格式化消息内容（支持换行等）
const formatMessageContent = (content) => {
  if (!content) return '';
  
  // 将换行符转换为<br>
  let formatted = content.replace(/\n/g, '<br>');
  
  // 简单的代码块处理
  formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre class="code-block">$1</pre>');
  
  // 简单的粗体处理
  formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  return formatted;
};

// 滚动到底部 - 优化动画和性能
const scrollToBottom = () => {
  if (messagesContainer.value) {
    // 使用平滑滚动提升用户体验
    messagesContainer.value.scrollTo({
      top: messagesContainer.value.scrollHeight,
      behavior: 'smooth'
    });
  }
};

// 处理Enter键
const handleEnterKey = (event) => {
  if (event.shiftKey) {
    // Shift + Enter 换行
    return;
  }
  // Enter 发送消息
  sendMessage();
};

// 发送消息
const sendMessage = () => {
  const message = newMessage.value.trim();
  if (!message || !conversationId.value) return;
  
  // 适配Dashboard.vue中的handleSendMessage函数
  emit('send-message', message);
  newMessage.value = '';
};

// 模拟流式输出
const simulateStreaming = (messageId, fullText, callback) => {
  let currentText = '';
  let index = 0;
  const speed = 30; // 每个字符的延迟时间（毫秒）
  
  const typeNextChar = () => {
    if (index < fullText.length) {
      currentText += fullText.charAt(index);
      index++;
      callback(messageId, currentText, 'loading');
      setTimeout(typeNextChar, speed);
    } else {
      // 完成流式输出
      callback(messageId, fullText, 'completed');
    }
  };
  
  // 开始流式输出
  typeNextChar();
};

// 复制消息
const copyMessage = async (content) => {
  try {
    await navigator.clipboard.writeText(content);
    
    // 显示复制成功提示
    copyNotification.value = '已复制到剪贴板';
    setTimeout(() => {
      copyNotification.value = '';
    }, 2000);
  } catch (err) {
    console.error('复制失败:', err);
  }
};

// 自动调整输入框高度
const adjustInputHeight = (event) => {
  const textarea = event.target;
  textarea.style.height = 'auto';
  textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'; // 最大高度限制
};

// 组件挂载后滚动到底部
onMounted(() => {
  // 延迟滚动，确保DOM完全渲染
  setTimeout(() => {
    scrollToBottom();
  }, 100);
  
  // 添加输入框事件监听
  const textarea = document.querySelector('.message-input');
  if (textarea) {
    textarea.addEventListener('input', adjustInputHeight);
    textarea.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });
  }
});
</script>

<style scoped>
.message-display {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  dark-mode: selector;
}

:dark .message-display {
  background: #111827;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

/* 空消息状态 */
.empty-messages {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  text-align: center;
  dark-mode: selector;
}

:dark .empty-messages {
  color: #9ca3af;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-messages h3 {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #374151;
  dark-mode: selector;
}

:dark .empty-messages h3 {
  color: #d1d5db;
}

.empty-messages p {
  font-size: 14px;
  max-width: 300px;
}

/* 消息列表 - 优化增量加载性能 */
.messages {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 为增量加载的消息添加淡入效果 */
.message-item {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 8px;
}

/* 用户消息 */
.user-message {
  flex-direction: row-reverse;
}

.user-message .message-content {
  background: #3b82f6;
  color: white;
  border-radius: 18px 18px 4px 18px;
  max-width: 70%;
  dark-mode: selector;
}

:dark .user-message .message-content {
  background: #2563eb;
}

/* 系统消息 */
.system-message .message-content {
  background: #f3f4f6;
  color: #1f2937;
  border-radius: 18px 18px 18px 4px;
  max-width: 70%;
  dark-mode: selector;
}

:dark .system-message .message-content {
  background: #374151;
  color: #f9fafb;
}

/* 头像 */
.message-avatar {
  flex-shrink: 0;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-avatar {
  background: #3b82f6;
  color: white;
  dark-mode: selector;
}

:dark .user-avatar {
  background: #2563eb;
}

.system-avatar {
  background: #f3f4f6;
  color: #6b7280;
  dark-mode: selector;
}

:dark .system-avatar {
  background: #374151;
  color: #d1d5db;
}

/* 消息内容 */
.message-content {
  padding: 12px 16px;
  word-wrap: break-word;
  position: relative;
}

.message-text {
  font-size: 14px;
  line-height: 1.5;
}

/* 加载状态 */
.message-loading {
  padding: 8px 0;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  background: currentColor;
  border-radius: 50%;
  opacity: 0.7;
  animation: pulse 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes pulse {
  0%, 80%, 100% {
    opacity: 0.7;
    transform: scale(0.8);
  }
  40% {
    opacity: 1;
    transform: scale(1);
  }
}

/* 错误状态 */
.message-error {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #ef4444;
  margin-top: 4px;
  dark-mode: selector;
}

:dark .message-error {
  color: #f87171;
}

/* 消息操作 */
.message-actions {
  flex-shrink: 0;
  opacity: 0;
  transition: opacity 0.2s;
}

.message-item:hover .message-actions {
  opacity: 1;
}

.action-button {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.05);
  color: #6b7280;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  dark-mode: selector;
}

:dark .action-button {
  background: rgba(255, 255, 255, 0.05);
  color: #9ca3af;
}

.action-button:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #374151;
  dark-mode: selector;
}

:dark .action-button:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #f3f4f6;
}

/* 输入区域 - 优化样式和稳定性 */
.input-area {
  padding: 20px;
  border-top: 1px solid #e5e7eb;
  background: white;
  dark-mode: selector;
  position: relative;
  z-index: 10;
}

:dark .input-area {
  border-top-color: #374151;
  background: #111827;
}

.input-wrapper {
  display: flex;
  gap: 8px;
  align-items: flex-end;
  position: relative;
}

.message-input {
  flex: 1;
  min-height: 44px;
  max-height: 120px;
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 22px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  outline: none;
  background: #f9fafb;
  transition: all 0.2s;
  dark-mode: selector;
}

:dark .message-input {
  border-color: #4b5563;
  background: #1f2937;
  color: #f3f4f6;
}

.message-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  background: white;
  dark-mode: selector;
}

:dark .message-input:focus {
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
  background: #1f2937;
}

.message-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.send-button {
  width: 44px;
  height: 44px;
  border: none;
  border-radius: 50%;
  background: #3b82f6;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  flex-shrink: 0;
}

.send-button:hover:not(:disabled) {
  background: #2563eb;
  transform: scale(1.05);
}

.send-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

.input-info {
  margin-top: 8px;
  font-size: 12px;
  color: #6b7280;
  text-align: center;
  dark-mode: selector;
}

:dark .input-info {
  color: #9ca3af;
}

.loading-text {
  color: #3b82f6;
  dark-mode: selector;
}

:dark .loading-text {
  color: #60a5fa;
}

/* 代码块样式 */
:deep(.code-block) {
  background: rgba(0, 0, 0, 0.05);
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
  margin: 8px 0;
  dark-mode: selector;
}

:dark :deep(.code-block) {
  background: rgba(0, 0, 0, 0.2);
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
  dark-mode: selector;
}

:dark .messages-container::-webkit-scrollbar-thumb {
  background: #4b5563;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
  dark-mode: selector;
}

:dark .messages-container::-webkit-scrollbar-thumb:hover {
  background: #6b7280;
}
</style>
